/*
 * Copyright (c) 2015 Minshenglife. All rights reserved. Minshenglife
 * PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 *
 */
package com.sentry.jobs;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.URL;

/**
 * @author WuBo (wub1@minshenglife.com)
 *
 */
public class HttpJob implements Job {

    private static final Logger LOGGER = LoggerFactory.getLogger(HttpJob.class);



    /*
     * (non-Javadoc)
     * 
     * @see org.quartz.Job#execute(org.quartz.JobExecutionContext)
     */
    @Override
    public void execute(JobExecutionContext context)
            throws JobExecutionException {
        String _url = context.getJobDetail().getJobDataMap().getString("url");
        long t1 = 0l;
        long t2 = 0l;
//        String jobName = context.getJobDetail().getKey().toString();
        try (Socket s = new Socket();) {
            URL url = new URL(_url);
            HTTPRequestHeaders header = new HTTPRequestHeaders(url);
            System.out.println(header.toString());
            t1 = System.nanoTime();
            s.connect(new InetSocketAddress(url.getHost(), 80));
            t2 = System.nanoTime();


            LOGGER.debug("url make connection use {}[us]",_url , t2-t1);
            
            t1 = System.nanoTime();
            try (OutputStream os = s.getOutputStream();
                    InputStream is = s.getInputStream();) {
                os.write(header.toString().getBytes());
                os.flush();

                
                is.read();
                os.close();
                is.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            s.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        t2 = System.nanoTime();

        LOGGER.debug("{} test ok , use {}[us]",_url,t2-t1);
    }

}
